package com.yonyou.pmclouds.enterprise.service.rmiimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseQueryParam;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseVO;
import com.yonyou.pmclouds.enterprise.mapper.EnterpriseMapper;
import com.yonyou.pmclouds.enterprise.rmiitf.EnterpriseQuery;
import com.yonyou.pmclouds.organization.entity.OrganizationVO;
import com.yonyou.pmclouds.organization.rmiitf.OrganizationQuery;
import com.yonyou.pmclouds.outter.tenant.TenantInfoServerQuery;
import com.yonyou.pmclouds.personnel.entity.PersonnelVO;
import com.yonyou.pmclouds.personnel.rmiitf.PersonnelQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.MessageFormat;
import java.util.*;

/**
 * @Author chulf
 * @Date 2020/4/13
 * @Description
 **/
@Slf4j
@Service(version = ApplicationConsts.APPLICATION_VERSION,interfaceClass = EnterpriseQuery.class)
public class EnterpriseQueryImpl implements EnterpriseQuery {
    @Autowired
    private TenantInfoServerQuery tenantInfoServerQuery;
    @Autowired
    private PersonnelQuery personnelQuery;
    @Autowired
    private EnterpriseMapper enterpriseMapper;
    @Autowired
    private OrganizationQuery organizationQuery;

    @Override
    public EnterpriseVO[] queryEnterprisesByUser(EnterpriseQueryParam param) throws BusinessException {
        //参数的初始化 为空赋值为null 以排除mapper中为null的判断
        if (param.getRoles() != null && param.getRoles().length == 0) param.setRoles(null);
        if (param.getPkOrgs() != null && param.getPkOrgs().length == 0) param.setPkOrgs(null);


        String loginUserId = RuntimeEnvironment.getLoginUserId();
        String tenantId = RuntimeEnvironment.getTenantId();

        if (StringUtils.isNotEmpty(loginUserId) && StringUtils.isNotEmpty(tenantId)) {

            boolean managerFlag = tenantInfoServerQuery.isManager(loginUserId, tenantId);

            if (managerFlag) {
                //企业管理员查询所有企业信息
                EnterpriseVO[] enterpriseVOS = enterpriseMapper.selectEtpsByCondition(param);
                //填充企业名称
                fillPkOrgNames(enterpriseVOS);
                return enterpriseVOS;
            }

            Set<String> etpPkS = personnelQuery.queryEtpsByUserId(loginUserId);

            if (!etpPkS.isEmpty()) {
                //企业联系人查询对应所有企业信息
                EnterpriseVO[] enterpriseVOS = enterpriseMapper.selectEtpsByPks(etpPkS.toArray(new String[0]));
                fillPkOrgNames(enterpriseVOS);
                return enterpriseVOS;
            }
            throw new BusinessException("您不是企业管理员或企业联系人");

        }
        log.info(MessageFormat.format("该租户{0}或用户id{1}为空",tenantId,loginUserId));
        throw new BusinessException("您没有对应人员档案的访问权限");

    }

    @Override
    public EnterpriseVO queryEnterpriseDetail(String pkEnterprise) throws BusinessException {

        EnterpriseVO[] enterpriseVOS = enterpriseMapper.selectEtpsByPks(new String[]{pkEnterprise});

        if (ArrayUtils.isEmpty(enterpriseVOS)) return null;
        fillPersonnel(enterpriseVOS[0]);

        fillPkOrgNames(enterpriseVOS);

        return enterpriseVOS[0];
    }

    @Override
    public EnterpriseVO[] queryEnterprisesByRole(byte role) throws BusinessException {

        EnterpriseQueryParam param = new EnterpriseQueryParam();

        param.setTenantId(RuntimeEnvironment.getTenantId());
        param.setRoles(new byte[]{role});

        EnterpriseVO[] enterpriseVOS = enterpriseMapper.selectEtpsByCondition(param);

        return enterpriseVOS;
    }

    @Override
    public EnterpriseVO[] queryByCondition(EnterpriseQueryParam param) {
        param.setTenantId(RuntimeEnvironment.getTenantId());

        EnterpriseVO [] enterpriseVOS = enterpriseMapper.selectByCondition(param);
        if(enterpriseVOS == null){
            enterpriseVOS = new EnterpriseVO[0];
        }

        return enterpriseVOS;
    }

    @Override
    public Map<String, EnterpriseVO[]> queryByUserIds(String[] userIds) throws BusinessException {
        if(userIds == null || userIds.length <= 0){
            return new HashMap<>();
        }

        PersonnelVO[] personnelVOS = personnelQuery.queryByUserIds(userIds);

        if(personnelVOS == null || personnelVOS.length <= 0){
            return new HashMap<>();
        }

        Set<String> pkEnterpriseSet = new HashSet<>();
        Map<String, Set<String>> userWithPkEnterpriseMap = new HashMap<>();
        for(PersonnelVO personnelVO : personnelVOS){
            pkEnterpriseSet.add(personnelVO.getPkEnterprise());
            Set<String> userWithPkEnterpriseSet = userWithPkEnterpriseMap.computeIfAbsent(personnelVO.getUserId(), k -> new HashSet<>());
            userWithPkEnterpriseSet.add(personnelVO.getPkEnterprise());
        }

        EnterpriseVO[] enterpriseVOS = enterpriseMapper.selectEtpsByPks(pkEnterpriseSet.toArray(new String[]{}));

        if(enterpriseVOS == null || enterpriseVOS.length <= 0){
            return new HashMap<>();
        }

        Map<String, EnterpriseVO> enterpriseVOMap = new HashMap<>();
        for(EnterpriseVO enterpriseVO : enterpriseVOS){
            enterpriseVOMap.put(enterpriseVO.getPkEnterprise(), enterpriseVO);
        }

        Map<String, EnterpriseVO[]> userWithEnterpriseMap = new HashMap<>();
        for(Map.Entry<String, Set<String>> entry : userWithPkEnterpriseMap.entrySet()){
            List<EnterpriseVO> enterpriseVOList = new ArrayList<>();
            for(String pkEnterprise : entry.getValue()){
                EnterpriseVO enterpriseVO = enterpriseVOMap.get(pkEnterprise);
                if(enterpriseVO == null){
                    continue;
                }
                enterpriseVOList.add(enterpriseVO);
            }

            if(enterpriseVOList.size() <= 0){
                continue;
            }

            userWithEnterpriseMap.put(entry.getKey(), enterpriseVOList.toArray(new EnterpriseVO[]{}));
        }


        return userWithEnterpriseMap;
    }

    @Override
    public EnterpriseVO[] queryByIds(String[] pkEnterprises) throws BusinessException {
        return enterpriseMapper.selectEtpsByPks(pkEnterprises);
    }

    /**
     *  填充人员信息
     * @param enterpriseVOS
     */
    private void fillPersonnel(EnterpriseVO enterpriseVOS){

        PersonnelVO[] personnelVOS = personnelQuery.queryPersonnelsByPkEtp(enterpriseVOS.getPkEnterprise());

        enterpriseVOS.setPersonnelVOS(personnelVOS);
    }

    /**
     *  填充组织名称
     * @param enterpriseVO
     * @throws BusinessException
     */
    private void fillPkOrgNames(EnterpriseVO[] enterpriseVO) throws BusinessException {

        if (enterpriseVO == null) return;

        HashSet<String> pkOrgs = new HashSet<>();

        for (EnterpriseVO vo : enterpriseVO) {
            if (vo.getPkOrgs() != null) pkOrgs.addAll(vo.getPkOrgs());
        }

        if (pkOrgs.isEmpty()) return;

        OrganizationVO[] organizationVOS = organizationQuery.queryByPkSrcs(RuntimeEnvironment.getTenantId(), pkOrgs.toArray(new String[0]));

        HashMap<String, OrganizationVO> pk2Org = new HashMap<>();
        for (OrganizationVO organizationVO : organizationVOS) {
            pk2Org.put(organizationVO.getPkSrc(),organizationVO);
        }

        for (EnterpriseVO vo : enterpriseVO) {
            List<String> tempPkOrg = vo.getPkOrgs();
            ArrayList<String> orgNames = new ArrayList<>();
            if (tempPkOrg == null || tempPkOrg.isEmpty()) continue;
            for (String pk : tempPkOrg) {
                OrganizationVO organizationVO = pk2Org.get(pk);
                if (organizationVO == null) continue;
                orgNames.add(organizationVO.getSname());
            }
            vo.setOrgNames(orgNames);
        }
    }
}
